package com.moji.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.moji.common.base.ApiResult;
import com.moji.common.entity.MyPage;
import com.moji.common.utils.PageUtil;
import com.moji.entity.SysDept;
import com.moji.entity.SysUser;
import com.moji.entity.dto.DeptSelectBoxDto;
import com.moji.entity.dto.PrOnOffDto;
import com.moji.entity.dto.TreeDto;
import com.moji.enums.MoJiEnumConfig;
import com.moji.mapper.SysDeptMapper;
import com.moji.service.SysDeptService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moji.service.SysUserService;
import com.moji.util.DeptTreeUtil;
import com.moji.util.MoJiCommonUtils;
import com.moji.util.ResultCode;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * <p>
 * 部门设置 服务实现类
 * </p>
 *
 * @author ccl
 * @since 2024-07-23
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements SysDeptService {

    @Resource
    private SysUserService sysUserService;

    @Override
    public boolean add(SysDept sysDept) {
        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDept::getDeptCode,sysDept.getParentCode());
        SysDept sysDeptP = this.getOne(wrapper);
        if(sysDeptP != null){
            SysDept sysDeptPNew = this.getOne(new LambdaQueryWrapper<SysDept>()
                    .eq(SysDept::getDeptName,sysDept.getDeptName())
                    .eq(SysDept::getParentCode,sysDept.getParentCode()));
            if(sysDeptPNew != null){
                throw new RuntimeException("部门名称重复,请核查!");
            }

            List<SysDept> deptList = this.list(new LambdaQueryWrapper<SysDept>()
                    .orderByDesc(SysDept::getDeptCode));
            //当前新增机构父级层级
            int level = sysDeptP.getDeptLevel();
            //当前新增机构父级path
            String path = sysDeptP.getDeptPath();
            //兄弟部门
            String brotherCode = deptList.get(0).getDeptCode();
            //兄弟排序
            int sort = deptList.get(0).getOrderNo();
            String deptCode = String.format("%04d", Long.parseLong(brotherCode)+1);
            sysDept.setDeptCode(deptCode);
            sysDept.setDeptPath(path+","+deptCode);
            sysDept.setOrderNo(sort+1);
            sysDept.setDeptLevel(level+1);
            sysDept.setParentName(sysDeptP.getParentName());
        }else{
            sysDept.setDeptCode(MoJiEnumConfig.CCP_SYSTEM_TOP_DEPT_CODE.getCode());
            sysDept.setDeptPath(MoJiEnumConfig.CCP_SYSTEM_TOP_DEPT_CODE.getCode());
            sysDept.setOrderNo(1);
            sysDept.setDeptLevel(1);
        }
        sysDept.setCreateTime(new Date());
        sysDept.setUpdateTime(new Date());
        sysDept.setPrOnoff(Integer.parseInt(MoJiEnumConfig.CCP_SYSTEM_PR_ON_ON.getCode()));
        sysDept.setUpdateId(MoJiCommonUtils.getUserCode());
        sysDept.setCreateId(MoJiCommonUtils.getUserCode());

        return this.save(sysDept);
    }

    @Override
    public boolean edit(SysDept sysDept) {
        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDept::getDeptName,sysDept.getDeptName())
                .eq(SysDept::getParentCode,sysDept.getParentCode());
        SysDept sysDeptP = this.getOne(wrapper);
        if(sysDeptP != null && !sysDept.getDeptName().equals(sysDeptP.getDeptName())){
            throw new RuntimeException("部门名称重复,请核查!");
        }
        sysDept.setUpdateTime(new Date());
        sysDept.setUpdateId(MoJiCommonUtils.getUserCode());
        return this.updateById(sysDept);
    }

    @Override
    public boolean delete(Long id) {
        SysDept sysDept = this.getById(id);
        if(sysDept ==null){
            throw new RuntimeException("数据不存在,请核查!");
        }
        if(MoJiEnumConfig.CCP_SYSTEM_TOP_DEPT_CODE.getCode().equals(sysDept.getDeptCode())){
            throw new RuntimeException("顶级部门不能删除,请核查!");
        }

        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysDept::getParentCode,sysDept.getDeptCode());
        List<SysDept> deptList = this.list(wrapper);
        if(ObjectUtil.isNotEmpty(deptList)){
            throw new RuntimeException("部门存在子部门，不能删除!");
        }

        LambdaQueryWrapper<SysUser> wrapper1 = new LambdaQueryWrapper();
        wrapper1.eq(SysUser::getDeptCode,sysDept.getDeptCode());
        List<SysUser> userList = sysUserService.list(wrapper1);
        if(ObjectUtil.isNotEmpty(userList)){
            throw new RuntimeException("部门已绑定人员，不能删除!");
        }
        return this.removeById(id);

    }

    @Override
    public MyPage<SysDept> queryPage(SysDept sysDept) {
        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
        if(ObjectUtil.isNotEmpty(sysDept.getDeptName())){
            wrapper.like(SysDept::getDeptName,sysDept.getDeptName());
        }
        if(ObjectUtil.isNotEmpty(sysDept.getDeptCode())){
            wrapper.like(SysDept::getDeptCode,sysDept.getDeptCode());
        }
        if(ObjectUtil.isNotEmpty(sysDept.getCode())){
            wrapper.like(SysDept::getDeptCode,sysDept.getCode());
        }
        wrapper.orderByDesc(SysDept::getUpdateTime);

        PageHelper.startPage(sysDept.getPageNum(), sysDept.getPageSize());
        List<SysDept> deptList = this.list(wrapper);
        PageInfo<SysDept> info = new PageInfo<>(deptList);
        return PageUtil.PageInfo2MyPage(info);
    }

    @Override
    public List<DeptSelectBoxDto> queryDeptSelectBox() {
        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
        List<SysDept> deptList = this.list(wrapper);
        List<DeptSelectBoxDto> listSelectBox = new ArrayList<>();
        DeptSelectBoxDto deptSelectBoxDao = null;
        if(ObjectUtil.isNotEmpty(deptList)){
            for(SysDept sysDept : deptList){
                deptSelectBoxDao = new DeptSelectBoxDto();
                deptSelectBoxDao.setDeptCode(sysDept.getDeptCode());
                deptSelectBoxDao.setDeptName(sysDept.getDeptName());
                listSelectBox.add(deptSelectBoxDao);
            }
        }
        return listSelectBox;
    }

    @Override
    public List<TreeDto> queryDeptTree() {
        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
        List<SysDept> sysDepts = this.list(wrapper);
        return DeptTreeUtil.list2Tree(sysDepts);

    }

    @Override
    public boolean updateStatus(PrOnOffDto prOnOffDao) {
        SysDept sysDept = this.getById(prOnOffDao.getId());
        if(sysDept != null){
            sysDept.setPrOnoff(Integer.parseInt(prOnOffDao.getPrOnOff()));
            sysDept.setPrOnoffTime(new Date());
        }
        return this.updateById(sysDept);
    }

    @Override
    public SysDept detail(Long id) {
        if(ObjectUtil.isEmpty(id)){
            throw new RuntimeException("主键ID不能为空,请核查!");
        }
        return this.getById(id);
    }

    @Override
    public List<TreeDto> queryPageTree(SysDept sysDept) {
        LambdaQueryWrapper<SysDept> wrapper = new LambdaQueryWrapper<>();
        if(ObjectUtil.isNotEmpty(sysDept.getDeptName())){
            wrapper.like(SysDept::getDeptName,sysDept.getDeptName());
        }
        if(ObjectUtil.isNotEmpty(sysDept.getDeptCode())){
            wrapper.like(SysDept::getDeptCode,sysDept.getDeptCode());
        }
        if(ObjectUtil.isNotEmpty(sysDept.getCode())){
            wrapper.like(SysDept::getDeptCode,sysDept.getCode());
        }
        List<SysDept> sysDepts = this.list(wrapper);
        return DeptTreeUtil.list2Tree(sysDepts);
    }
}
